package com.cwt_taxi_xa.protocol;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;

import com.cwt_taxi_xa.ActivityEnd;
import com.cwt_taxi_xa.ActivityMain;
import com.cwt_taxi_xa.ActivityWaitQD;
import com.cwt_taxi_xa.MainApplication;
import com.cwt_taxi_xa.constants.Constants;
import com.cwt_taxi_xa.constants.ConstantsState;
import com.cwt_taxi_xa.constants.MyStatus;
import com.cwt_taxi_xa.constants.SPConstants;
import com.cwt_taxi_xa.data.DataUtil;
import com.cwt_taxi_xa.db.bll.LocalInfoBiz;
import com.cwt_taxi_xa.model.AaData;
import com.cwt_taxi_xa.model.LocalInfo;
import com.cwt_taxi_xa.protocol.CardUtil.CheckCardListener;
import com.cwt_taxi_xa.record.RecordTimer;
import com.cwt_taxi_xa.record.RecorderBiz;
import com.cwt_taxi_xa.service.SerialPortService;
import com.cwt_taxi_xa.util.AppLog;
import com.cwt_taxi_xa.util.DateUtil;
import com.cwt_taxi_xa.util.ExceptionUtil;
import com.cwt_taxi_xa.util.SPUtils;
import com.cwt_taxi_xa.util.TTsFunction;
import com.cwt_taxi_xa.util.Tools;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;


/**
 *
 * 项目名称：Dss_CarCall_Sz 类名称：MeterBusinessProcess 类描述： 创建人：Administrator
 * 创建时间：2016-5-31 上午10:35:10 修改人：Administrator 修改时间：2016-5-31 上午10:35:10 修改备注：
 *
 * @version 1.0
 *
 */
public class MeterBusinessProcess {

	private static final String TAG = "MeterBusinessProcess";
	private static long last00e7Time = 0;
	private static long last00e8Time = 0;
	private static long last00e3Time = 0;


	public static String carNumber;
	public static String companyCode;
	public static String driverQualificationCode;

	public static ArrayList<String> historyBoardingTime = null;

	/**
	 * 处理计价器相关业务
	 *
	 * @param aaData
	 * @param context
	 */
	public static synchronized void processMeter(AaData aaData, Context context) {

		try {
			int dstPos = 0;
			int mid = aaData.getMid();
			ArrayList<Object> dataList = aaData.getDataList();

			switch (mid) {
				case 0x00E9: // 计价器心跳应答
					try {
						SerialPortService.getInstance().sendSerialData6(EncoderSZ55aa.meterHeartAnswer());

					} catch (Exception e) {
						// TODO: handle exception
						AppLog.i(ExceptionUtil.getInfo(e));
					}
					break;


//			case 0x0034: // 2.1 计价器状态查询指令（实现应答）
//				try {
//					// 进入空车时间
//					String time = (String) dataList.get(dstPos++);
//
//					ConstantsState.setStateValue(5, "0");
//					ConstantsState.setStateValue(6, "1");
//					ConstantsState.setStateValue(9, "0");
//
//				} catch (Exception e) {
//					// TODO: handle exception
//					AppLog.i(ExceptionUtil.getInfo(e));
//				}
//				break;

				case 0x00E7: // 重车，单次运营开始
					try {

						long currentTime = System.currentTimeMillis();
						long timeBetween = currentTime - last00e7Time;
						// 防止计价器连续快速发送多条数据
						if (timeBetween < 2000) {
							// System.out.println("==========计价器A008 驳回连续数据");
							return;
						}

						last00e7Time = currentTime;

						SerialPortService.getInstance().sendSerialData6(EncoderSZ55aa.getMeterDtuBody("00E7", Tools.parseHexStr2Byte("90")));

						// int serialnumber = (Integer) dataList.get(1);
						// // if(serialnumber != Constants.TRAIN_SERIAL_NUMBER){
						//

						new Thread(new Runnable() {
							@Override
							public void run() {
								for (int i = 0; i < 3; i++) {
									try {
										AppLog.e("重车通知顶灯");
										DDUtil.sendText2TT(5);
										Thread.sleep(1000);
									} catch (Exception e) {
										e.printStackTrace();
									}
								}
							}
						}).start();

						//
						// Constants.TRAIN_SERIAL_NUMBER = serialnumber;
						//
						// 运营数据发送标志true
//					Constants.OPER_DATA_SEND_FLAG = true;
						//
						// 进入重车时间
						String intoFullTime = (String) dataList.get(0);

						Log.e("运营开始-进入重车时间", intoFullTime);

						BusinessFactory.aboardLocationData = EncoderUtil.getLocationInformationByte();
						//
						MyStatus.zhongche = true;
						MCUUtil.mVehicleInformation.softWareMeter.start();
						ConstantsState.setStateValue(9, "1");

						// 录音
						RecordTimer.mediaIdList = new ArrayList<String>();
						if(RecorderBiz.getRecordType() == 2 && RecordTimer.recordReason != 2){
						/*RecorderInfo recordingInfo = new RecorderInfo(0);
						SystemRecord.doRecord(recordingInfo);*/
							RecordTimer.recordReason = 0;
							SerialPortService.handler.obtainMessage(1005).sendToTarget();
						}

						Activity top = MainApplication.getInstance().topActivity;
						if(top!=null&&!(top instanceof ActivityMain)){
							top.startActivity(new Intent(top, ActivityMain.class));
						}
						while (true) {
							if(MainApplication.topActivity instanceof ActivityMain){
								MainApplication.topActivity.sendMsg(1008, null);
								break;
							}
						}

						 // 拍照

						//6-15，处理没做好，在dvr不连接的时候会导致死循环崩溃，另外照片保存后没清理环节
//						Intent intent = new Intent(FloatService.action_camera);
//						intent.putExtra("type", 4);
//						intent.putExtra("seq", 0);
//						intent.putExtra("w", 320);
//						intent.putExtra("h", 240);
//						MainApplication.topActivity.sendBroadcast(intent);



						 /*PhotoInfo info = new PhotoInfo(4);
						 CameraManager.takeAPhoto(info);*/
						//
						// // 录音
						// if(RecordBiz.getRecordType() == 2){
						// RecordingInfo recordingInfo = new RecordingInfo(0);
						// SystemRecord.doRecord(recordingInfo);
						// }
						//
						// TTsFunction.speakOneTime("尊敬的乘客,您好,本车支持使用支付宝支付打车费用,欢迎您使用");
						//
//					try {
//						Intent intent = new Intent(context, DriverInfoCard.class);
//						intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//						// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//						intent.putExtra("load", 1);
//						context.startActivity(intent);
//					} catch (Exception e) {
//						e.printStackTrace();
//						AppLog.e(ExceptionUtil.getInfo(e), e);
//					}

						ConstantsState.setStateValue(5, "1");		//设置空转重
						ConstantsState.setStateValue(6, "0");
						ConstantsState.setStateValue(9, "1");
						AppLog.e("------------------------1");
						if (SPUtils.getParamBoolean(SPConstants.SPK_00E7_TTS,false)){
							if (!"".equals(SPUtils.getParamString(SPConstants.SPK_00E7_TTS_CONTENT,""))){
								AppLog.e("------------------------2");
								int	year = Integer.parseInt(new SimpleDateFormat("yy").format(new Date()));
								int month = Integer.parseInt(new SimpleDateFormat("MM").format(new Date()));
								int day = Integer.parseInt(new SimpleDateFormat("dd").format(new Date()));

								String effs = SPUtils.getParamString(SPConstants.SPK_00E7_TTS_STARTTIME,"");
								String effe = SPUtils.getParamString(SPConstants.SPK_00E7_TTS_ENDTIME,"");
								if (effs != null && !"0".equals(effs) && effe != null && "0".equals(effe)){
									AppLog.e("------------------------3");
									int effsY = Integer.parseInt(effs.substring(0,2));
									int effsM = Integer.parseInt(effs.substring(2,4));
									int effsD = Integer.parseInt(effs.substring(4,6));

									int effeY = Integer.parseInt(effe.substring(0,2));
									int effeM = Integer.parseInt(effe.substring(2,4));
									int effeD = Integer.parseInt(effe.substring(4,6));

									if (year >= effsY && year <= effeY){
										if (month >= effsM && month <= effeM){
											if (day >= effsD && day <= effeD){
												MainApplication.getInstance().handler.postDelayed(new Runnable() {

													@Override
													public void run() {
														try {
															AppLog.e("------------------------4");
																TTsFunction.speakText(SPConstants.SPK_00E7_TTS_CONTENT);
														} catch (Exception e) {
															e.printStackTrace();
														}
													}
												},SPUtils.getParamInteger(SPConstants.SPK_00E7_TTS_DELAY,20) * 1000);
												
											}
										}
									}

								}

							}
						}

						// }
						welcomeToRide();
					} catch (Exception e) {
						// TODO: handle exception
						AppLog.i(ExceptionUtil.getInfo(e));
					}
					break;
				case 0x0030: // 停车收费
					try {
						//
						byte[] meterData = (byte[]) dataList.get(dstPos++);
					} catch (Exception e) {
						// TODO: handle exception
						AppLog.i(ExceptionUtil.getInfo(e));
					}

				case 0x00E8: // 上传运营数据
					try {

						SerialPortService.getInstance().sendSerialData6(EncoderSZ55aa.getMeterDtuBody("00E8", Tools.parseHexStr2Byte("90")));

						long currentTime = System.currentTimeMillis();
						long timeBetween = currentTime - last00e8Time;
						// 防止计价器连续快速发送多条数据
						if (timeBetween < 10000) {
							return;
						}

						last00e8Time = currentTime;


						// 车牌号
						String str1 = (String) dataList.get(1);
						Log.e("单次运营结束", "车牌号-" + str1);
						DeviceBiz.setCarNumber(str1);
						DeviceBiz.setCarNumberCorrection(false);
						// 经营许可证号
						String str2 = (String) dataList.get(2);
						Log.e("单次运营结束", "经营许可证号-" + str2);
						// 司机从业资格证号
						String str3 = (String) dataList.get(3);
						Log.e("单次运营结束", "司机从业资格证号-" + str3);
						// 上车时间
						String str4 = (String) dataList.get(4);
						Log.e("单次运营结束", "上车时间（原始数据）-" + str4);
						String date_e8 = "20"+str4.substring(0, 2)+"年"+str4.substring(2, 4)+"月"+str4.substring(4, 6)+"日 ";
						str4 = date_e8+str4.substring(6, 8)+":"+str4.substring(8, 10);
						Log.e("单次运营结束", "上车时间-" + str4);
						// 下车时间
						String str5 = (String) dataList.get(5);
						str5 = date_e8+str5.substring(0, str5.length()-2)+":"+str5.substring(str5.length()-2, str5.length());
						Log.e("单次运营结束", "下车时间-" + str5);
						// 计程公里
						String str6 = (String) dataList.get(6);
						int in6 = Integer.parseInt(str6);
						if(in6>9){
							str6 = (in6/10)+"."+(in6%10);
						}else{
							str6 = "0."+in6;
						}
						Log.e("单次运营结束", "计程公里-" + str6);
						// 空驶里程
						String str7 = (String) dataList.get(7);
						Log.e("单次运营结束", "空驶里程-" + str7);
						// 附加费
						String str8 = (String) dataList.get(8);
						Log.e("单次运营结束", "附加费-" + str8);
						// 记时时间
						String str9 = (String) dataList.get(9);
						Log.e("单次运营结束", "记时时间-" + str9);
						// 交易金额
						String str10 = (String) dataList.get(10);
						int in10 = Integer.parseInt(str10);
						ActivityMain.saveTodayyy(in10);
						if(in10>9){
							str10 = (in10/10)+"."+(in10%10);
						}else{
							str10 = "0."+in10;
						}
						Log.e("单次运营结束", "交易金额-" + str10);
						// 当前车次
						int i1 = (Integer) dataList.get(11);
						Log.e("单次运营结束", "当前车次-" + i1);

						//临时处理营运数据异常
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
						String today = sdf.format(new Date());
						String lsct = SPUtils.getParamString("lastsavect", "");
						if(!today.equals(lsct)){
							SPUtils.setParam("lastsavect", today);
							SPUtils.setParam(SPConstants.SPK_cartimes, i1);
							AppLog.e("---------保存当日首次运营车次时间："+today+"    车次："+i1);
						}

						// 交易类型
						int i2 = (Integer) dataList.get(12);
						Log.e("单次运营结束", "交易类型-" + i2);

						// 车次
						int trainnumber = Integer.parseInt(dataList.get(11).toString());

						new Thread(new Runnable() {
							@Override
							public void run() {
								for (int i = 0; i < 3; i++) {
									try {
										AppLog.e("顶灯"+i);
										DDUtil.sendText2TT(1);
										Thread.sleep(2000);
									} catch (Exception e) {
										e.printStackTrace();
									}
								}
							}
						}).start();

//					Constants.TRAIN_NUMBER = trainnumber;
						// 弹出金额界面
						String amount = Tools.intChangeString(Integer.parseInt(dataList.get(10).toString()), 100);

						BusinessFactory.goOffLocationData = EncoderUtil.getLocationInformationByte();
						byte[] goOffdata = (byte[]) dataList.get(0);
						BusinessFactory.meterSingleBusinessData = goOffdata;
						MyStatus.zhongche = false;
						ConstantsState.setStateValue(9, "0");

						// 拍照
						/*
						 * PhotoInfo info = new PhotoInfo(5);
						 * CameraManager.takeAPhoto(info);
						 */
						MCUUtil.mVehicleInformation.softWareMeter.stop();
						String result = str10+"-"+str6+"-"+str4+"-"+str5+"-"+str9+"-"+str1;
						Activity top = MainApplication.getInstance().topActivity;
						if(top!=null&&!(top instanceof ActivityMain)){
							top.startActivity(new Intent(top, ActivityMain.class));
						}
						while (true) {
							if(MainApplication.getInstance().topActivity instanceof ActivityMain){
								MainApplication.getInstance().topActivity.sendMsg(1010, result);//刷新时间把时间中转给评价解码
								break;
							}
						}

//					Intent intent = new Intent(context, Checkstand.class);
//					intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//					intent.putExtra("amount", amount);
//					context.startActivity(intent);

						ConstantsState.setStateValue(5, "0");
						ConstantsState.setStateValue(6, "1");		//重转空
						ConstantsState.setStateValue(9, "0");

						if (SPUtils.getParamBoolean(SPConstants.SPK_00E8_TTS,false)){
							if (!"".equals(SPUtils.getParamString(SPConstants.SPK_00E8_TTS_CONTENT,""))){
								int	year = Integer.parseInt(new SimpleDateFormat("yy").format(new Date()));
								int month = Integer.parseInt(new SimpleDateFormat("MM").format(new Date()));
								int day = Integer.parseInt(new SimpleDateFormat("dd").format(new Date()));

								String effs = SPUtils.getParamString(SPConstants.SPK_00E7_TTS_STARTTIME,"");
								String effe = SPUtils.getParamString(SPConstants.SPK_00E7_TTS_ENDTIME,"");
								if (effs != null && !"0".equals(effs) && effe != null && "0".equals(effe)){
									int effsY = Integer.parseInt(effs.substring(0,2));
									int effsM = Integer.parseInt(effs.substring(2,4));
									int effsD = Integer.parseInt(effs.substring(4,6));

									int effeY = Integer.parseInt(effe.substring(0,2));
									int effeM = Integer.parseInt(effe.substring(2,4));
									int effeD = Integer.parseInt(effe.substring(4,6));

									if (year >= effsY && year <= effeY){
										if (month >= effsM && month <= effeM){
											if (day >= effsD && day <= effeD){
												MainApplication.getInstance().handler.postDelayed(new Runnable() {

													@Override
													public void run() {
														try {
															if (!TTsFunction.TTS_Playing){
																TTsFunction.speakText(SPConstants.SPK_00E8_TTS_CONTENT);
															}
														} catch (Exception e) {
															e.printStackTrace();
														}
													}
												},SPUtils.getParamInteger(SPConstants.SPK_00E8_TTS_DELAY,20) * 1000);
											}
										}
									}

								}

							}
						}

//					if (DriverInfoCard.instance != null) {
//						DriverInfoCard.instance.finish();
//					}

						/*
						 * //发送运营数据至服务器 if(Constants.OPER_DATA_SEND_FLAG){
						 * DispatchCenterUsers
						 * .witeMsg(Encoder.getBusinessDataUplpad
						 * (1,"01","000000"),0); Constants.OPER_DATA_SEND_FLAG =
						 * false; }
						 */

						// 发送协议给评价器，提示评价
//					SendDateToSerial.witeSerialInfo("发送协议给评价器，提示评价", QyeEncoder.operEvaluate("01"));
					} catch (Exception e) {
						// TODO: handle exception
//					AppLog.i(ExceptionUtil.getInfo(e));
						e.printStackTrace();
					}
					break;

				case 0x00F2: // 运营数据补传
					try {
						// 车次
						int trainnumber = Integer.parseInt(dataList.get(11).toString());
//					Constants.TRAIN_NUMBER = trainnumber;
						// 弹出金额界面
						String amount = Tools.intChangeString(Integer.parseInt(dataList.get(10).toString()), 100);

						BusinessFactory.goOffLocationData = EncoderUtil.getLocationInformationByte();
						byte[] goOffdata = (byte[]) dataList.get(0);
						BusinessFactory.meterSingleBusinessData = goOffdata;

//					Constants.KONG_ZHONG_STATE = 1;

						// 拍照
						// PhotoInfo info = new PhotoInfo(5);
						// CameraManager.takeAPhoto(info);

						ConstantsState.setStateValue(5, "0");
						ConstantsState.setStateValue(6, "1");		//重转空
						ConstantsState.setStateValue(9, "0");

						SerialPortService.getInstance().sendSerialData6(EncoderSZ55aa.getMeterDtuBody("00F2", Tools.parseHexStr2Byte("90")));

						// 发送运营数据至服务器
						//DispatchCenterUsers.witeMsg(Encoder.getBusinessDataUplpad(0, trainnumber, "000000"), 0);
						//MCUUtil.mVoiceTool.dispatchViolation(4);
					} catch (Exception e) {
						// TODO: handle exception
						AppLog.i(ExceptionUtil.getInfo(e));
					}
					break;
				case 0x00E0: // 请求开机
					try {
						AppLog.savelog("处理计价器指令：   mid："+mid+"   0004");
						AppLog.d(TAG, "处理计价器指令：   mid："+mid);
						// 开机标识
						int flag = (Integer) dataList.get(dstPos++);
						AppLog.d(TAG, "请求开机指令：   flag:" + flag);
						AppLog.savelog("请求开机指令：   flag:" + flag);
						// // 车牌号
						// String carNumber = (String) dataList.get(dstPos++);
						if (flag == 0x90) {
							AppLog.savelog("处理计价器指令：   mid："+mid+"   0005");
							AppLog.d(TAG, "处理计价器指令：   mid："+mid+"   0005");
							// SendDateToSerial.witeSerialInfo("结果通用应答-计价器请求开机ACK",
							// EncoderSZ55aa.answerResult(String.valueOf(mid),
							// SerialConstants.ACK));
							// 读取驾驶员信息并发送给计价器
							/**
							 * 发送驾驶员从业资格信息
							 *
							 * @param companyCode
							 *            经营许可证号 BYTE[16]
							 * @param deriverCode
							 *            从业资格证号 BYTE[19]
							 * @param carNumber
							 *            车牌号 BYTE[6]
							 * @param time
							 *            刷卡时间 YYYYMMDDHHMM
							 * @param deviceStatus
							 *            终端状态 BYTE[2]
							 * @param lockTime
							 *            公司锁表时间限制 YYYYMMDDHH 全0表示无限制
							 * @param lockCount
							 *            公司运营次数限制 0000表示无限制
							 * @param result
							 *            操作结果
							 * @return
							 */
							Log.e("MeterBusinessProcess", "收到计价器开机请求");
//						MainApplication.getInstance().topActivity.sendMsg(1003, null);


//						if(!(MainApplication.topActivity instanceof ActivityCamera)){
//							TTsFunction.speakText("计价器申请开机，请看摄像头完成人证对比");
//							MainApplication.topActivity.startActivity(new Intent(MainApplication.topActivity, ActivityCamera.class));
//						}
							AppLog.d(TAG, "收到计价器开机请求 ActivityWaitQD.face:" + ActivityWaitQD.face);
							AppLog.savelog( "收到计价器开机请求 ActivityWaitQD.face:" + ActivityWaitQD.face);
							if(ActivityWaitQD.face){
								AppLog.savelog("处理计价器指令：   mid："+mid+"   0006");
								AppLog.d(TAG, "处理计价器指令：   mid："+mid+"   0006");
								//ActivityWaitQD.face = false;
								SerialPortService.getInstance()
										.sendSerialData6(
												MeterEncoder.sendDriverInfoForPower905("00E0",
//											"12345",
//											"12345",
														Constants.sijiinfo.getQiyecode(),
														Constants.sijiinfo.getSijicode(),
														SPUtils.getParamString(SPConstants.SPK_carcode, SPConstants.SPV_carcode),
														DateUtil.getNowDateToMeter(), 1,
														SPUtils.getParamString(SPConstants.PARAMS_METER_USEABLE_TIME,"0000000000"),
														SPUtils.getParamString(SPConstants.PARAMS_METER_USEABLE_COUNT,"0000"),
														"90"));
							}


						} else {
							AppLog.savelog("处理计价器指令：   mid："+mid+"   0007");
							AppLog.d(TAG, "处理计价器指令：   mid："+mid+"   0007");
							// SendDateToSerial.witeSerialInfo("结果通用应答-计价器请求开机NAK",
							// EncoderSZ55aa.answerResult(String.valueOf(mid),
							// SerialConstants.NAK));
						}
					} catch (Exception e) {
						// TODO: handle exception
						AppLog.i(ExceptionUtil.getInfo(e));
						AppLog.savelog("处理计价器指令：   mid："+mid+"   0008");
					}
					break;
				case 0x0001: // 开机发送驾驶员从业资格信息应答
					try {
						// 操作结果
						int result = (Integer) dataList.get(dstPos++);
					} catch (Exception e) {
						// TODO: handle exception
						AppLog.i(ExceptionUtil.getInfo(e));
					}
					break;
				case 0x00E1: // 开机结果
					try {
						// 单位代码
						String companyCode = (String) dataList.get(dstPos++);
						AppLog.e("单位代码-" + companyCode);
						// 从业资格证号
						String driverCode = (String) dataList.get(dstPos++);
						AppLog.e("从业资格证号-" + driverCode);
						// 车牌号
						String carNumber = (String) dataList.get(dstPos++);
						AppLog.e("车牌号-" + carNumber);
						// 计价器开机时间
						String time = (String) dataList.get(dstPos++);
						AppLog.e("计价器开机时间-" + time);
						// 总运营次数
						int count = (Integer) dataList.get(dstPos++);
						AppLog.e("总运营次数-" + count);
						// 操作结果
						int result = (Integer) dataList.get(dstPos++);
						AppLog.e("计价器开机结果-" + Integer.toHexString(result));
						AppLog.savelog("计价器开机结果-" + Integer.toHexString(result));
						if(result==0x90){
							// 操作结果
							byte[] signInfo = (byte[]) dataList.get(dstPos++);



//					DriverInfoBiz.requestCount = 0;
//					DriverInfoBiz.saveCurrentDriverCode(driverCode);
//					DriverInfoBiz.setCurrentDriver(null);

							MainApplication.getInstance().topActivity.sendMsg(1004, null);
							DDUtil.sendText2TT(1);

//					Intent intent = new Intent(context, DriverInfoCard.class);
//					intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//					//					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//					intent.putExtra("load", 0);
//					context.startActivity(intent);
							// 上班签到
							byte[] message = Encoder.getCheckIn(signInfo);
							LocalInfo info = new LocalInfo(LocalInfo.TYPE_CHECK_IN);
							info.setData(Tools.parseByte2HexStr(message));
							LocalInfoBiz.getInstance().addInfo(info);
							LocalInfoBiz.getInstance().postCheckInfo();
						}


					} catch (Exception e) {
						// TODO: handle exception
						AppLog.i(ExceptionUtil.getInfo(e));
					}
					break;
				case 0x00E3: // 请求关机
					// 防止计价器连续快速发送多条数据
					if (System.currentTimeMillis()-last00e3Time < 5000) {
						return;
					}
					last00e3Time = System.currentTimeMillis();
					try {
						// 标识
						int flag = (Integer) dataList.get(dstPos++);
						AppLog.d(TAG, "请求关机指令：   flag:" + flag);
						AppLog.savelog("请求关机指令：   flag:" + flag);
						if (flag == 0x90) {
							// SendDateToSerial.witeSerialInfo("结果通用应答-计价器请求关机ACK",EncoderSZ55aa.answerResult(String.valueOf(mid),
							// SerialConstants.ACK));
							// 读取驾驶员信息并发送给计价器
//						if(MainApplication.getInstance().topActivity instanceof ActivityQT){
//							MainApplication.getInstance().topActivity.sendMsg(1005, null);
//						}else{
//							Activity top = MainApplication.getInstance().topActivity;
//							Intent intent = new Intent(top, ActivityQT.class);
//							intent.putExtra("type", 1);
//							top.startActivity(intent);
//						}


							//不再去判断，全都能直接签退
//						if(SPUtils.getParamBoolean(SPConstants.SPK_canSignOut, SPConstants.SPV_canSignOut)){

							if(carNumber!=null&&carNumber.length()>0){
								AppLog.d(TAG, "SPK_ScardExist:" + SPUtils.getParamBoolean(SPConstants.SPK_ScardExist, SPConstants.SPV_ScardExist));
								if(SPUtils.getParamBoolean(SPConstants.SPK_ScardExist, SPConstants.SPV_ScardExist)){
									CardUtil.CheckCard(new CheckCardListener() {
										@Override
										public void onReadCard(String sijiCode) {
											AppLog.d(TAG, "SPK_ScardExist sijiCode:" + sijiCode + " driverQualificationCode:" + driverQualificationCode);
											if(sijiCode.equals(driverQualificationCode)){
												SerialPortService.getInstance().sendSerialData6(MeterEncoder.sendDriverInfoForPower905("00E3",
														companyCode,
														driverQualificationCode,
														carNumber,
														DateUtil.getNowDateToMeter(), 1,
														SPUtils.getParamString(SPConstants.PARAMS_METER_USEABLE_TIME,"0000000000"),
														SPUtils.getParamString(SPConstants.PARAMS_METER_USEABLE_COUNT,"0000"),
														"90"));
												new Thread(new Runnable() {
													@Override
													public void run() {
														try {
															Thread.sleep(2200);
														} catch (InterruptedException e) {
															e.printStackTrace();
														}
														TTsFunction.speakText("请移除从业资格证卡片");
													}
												}).start();
											}else{
												TTsFunction.speakText("签退司机卡和签到司机卡不同");
											}
											CardUtil.listener = null;
										}
										@Override
										public void onCardUnExist() {
											TTsFunction.speakText("未检测到从业资格证");
											CardUtil.listener = null;
										}
									});
								}else{
									SerialPortService.getInstance().sendSerialData6(MeterEncoder.sendDriverInfoForPower905("00E3",
											companyCode,
											driverQualificationCode,
											carNumber,
											DateUtil.getNowDateToMeter(), 1,
											SPUtils.getParamString(SPConstants.PARAMS_METER_USEABLE_TIME,"0000000000"),
											SPUtils.getParamString(SPConstants.PARAMS_METER_USEABLE_COUNT,"0000"),
											"90"));
								}

							}else{
								new Thread(new Runnable() {
									@Override
									public void run() {
										for (int i = 0; i < 5; i++) {
											try {
												Thread.sleep(1000);
												SerialPortService.getInstance().sendSerialData6(MeterEncoder.queryMeterState());
											} catch (Exception e) {
											}
										}
										if(DataUtil.getJJQ()==1){
											TTsFunction.speakText("请重新按IC键两秒签退");
										}else if(DataUtil.getJJQ()==2){
											TTsFunction.speakText("请重新按单程键3秒签退");
										}else if(DataUtil.getJJQ()==3){
											TTsFunction.speakText("请重新按暂停键两秒松开");
										}
									}
								}).start();
							}
//						}



						} else {
							// SendDateToSerial.witeSerialInfo("结果通用应答-计价器请求关机NAK",EncoderSZ55aa.answerResult(String.valueOf(mid),
							// SerialConstants.NAK));
						}
					} catch (Exception e) {
						// TODO: handle exception
						AppLog.i(ExceptionUtil.getInfo(e));
					}
					break;
				case 0x00F1: // 原当班数据汇总补传---通用计价器如果有未合理提交的运营数据，会当做关机结果上传，会连续上传多条----------
				case 0x00E4: // 关机结果
					try {
						// 签退数据所需计价器数据
						byte[] meterData = (byte[]) dataList.get(dstPos++);
						// 单位代码 BCD[16]
						String companyCode = (String) dataList.get(dstPos++);
						AppLog.e("单位代码-" + companyCode);
						// 司机代码 BCD[19] 车辆自编号+司机编码，6位，不足的前面补0
						String driverCode = (String) dataList.get(dstPos++);
						AppLog.e("司机代码-" + driverCode);
						// 自编号 BYTE[6] 车辆自编号，5位，前面补0，ASCII字符
						String selfCode = (String) dataList.get(dstPos++);
						AppLog.e("车牌号-" + selfCode);
						// 脉冲数 BCD[2] 格式为XXXX，最大9999，暂时填0
						String mcs = (String) dataList.get(dstPos++);
						AppLog.e("计价器K值-" + mcs);
						// 当班开机时间 BCD[6] YYYY-MM-DD-hh-mm
						// 当班关机时间 BCD[6] YYYY-MM-DD-hh-mm
						String powerOnTime = (String) dataList.get(dstPos++);
						String powerOffTime = (String) dataList.get(dstPos++);
						try {
							powerOnTime = powerOnTime.substring(0, 4)+"年"+powerOnTime.substring(4, 6)+"月"+powerOnTime.substring(6, 8)+" "+powerOnTime.substring(8, 10)+":"+powerOnTime.substring(10, 12);
						} catch (Exception e) {
						}
						try {
							powerOffTime = powerOffTime.substring(0, 4)+"年"+powerOffTime.substring(4, 6)+"月"+powerOffTime.substring(6, 8)+" "+powerOffTime.substring(8, 10)+":"+powerOffTime.substring(10, 12);
						} catch (Exception e) {
						}
						AppLog.e("当班开机时间-" + powerOnTime);
						AppLog.e("当班关机时间-" + powerOffTime);
						// 当班公里 BCD[3] 格式为XXXXX.X公里
						String KM = (String) dataList.get(dstPos++);
						int intkm = Integer.parseInt(KM);
						if(intkm>9){
							KM = (intkm/10)+"."+(intkm%10);
						}else{
							KM = "0."+intkm;
						}
						AppLog.e("当班公里-" + KM);
						// 当班营运公里 BCD[3] 格式为XXXXX.X公里
						String busiKM = (String) dataList.get(dstPos++);
						int intbskm = Integer.parseInt(busiKM);
						if(intbskm>9){
							KM = (intbskm/10)+"."+(intbskm%10);
						}else{
							KM = "0."+intbskm;
						}
						AppLog.e("当班营运公里-" + busiKM);
						// 车次 BCD[2] 格式为XXXX，最大9999（保留，填0）
						String carCount = (String) dataList.get(dstPos++);
						AppLog.e("车次-" + carCount);
						// 计时时间 BCD[3] hh-mm-ss（总计费时间），是部标内容，有业务需求，请确认能否上传
						String tardeTime = (String) dataList.get(dstPos++);
						AppLog.e("计时时间-" + tardeTime);
						// 总计金额 BCD[3] 格式XXXXX.X元
						String totalAmount = (String) dataList.get(dstPos++);
						int inttotalAmount = Integer.parseInt(totalAmount);
						if(inttotalAmount>9){
							totalAmount = (inttotalAmount/10)+"."+(inttotalAmount%10);
						}else{
							totalAmount = "0."+inttotalAmount;
						}
						AppLog.e("总计金额-" + totalAmount);
						// 卡收金额 BCD[3] 格式XXXXX.X元
						String cardAmount = (String) dataList.get(dstPos++);
						AppLog.e("卡收金额-" + cardAmount);
						// 卡次 BCD[2] 袼式为XXKX，最大9999
						String cardCount = (String) dataList.get(dstPos++);
						AppLog.e("卡次-" + cardCount);
						// 班间公里 BCD[2] 格式XXX.X公里（上一班签退到本班签 到的公里数）
						String nightKM = (String) dataList.get(dstPos++);
						AppLog.e("班间公里-" + nightKM);
						// 总计公里 BCD[3] 格式为XXXXX.X公里（计价器安装后累积）
						String totalKM = (String) dataList.get(dstPos++);
						AppLog.e("总计公里-" + totalKM);
						// 总营运公里 BCD[3] 格式为XXXXX.X公里（计价器安装后累积）
						String totalBusiKM = (String) dataList.get(dstPos++);
						AppLog.e("总营运公里-" + totalBusiKM);
						// 单价 BCD[2] 格式XX.XX元
						String price = (String) dataList.get(dstPos++);
						AppLog.e("单价-" + price);
						// 总营运次数 UINT32 高位在前，低位在后
						int totalBusiCount = (Integer) dataList.get(dstPos++);
						AppLog.e("总营运次数-" + totalBusiCount);


						SerialPortService.getInstance().sendSerialData6(EncoderSZ55aa.getMeterDtuBody("00"+Integer.toHexString(mid), Tools.parseHexStr2Byte("90")));

//					MainApplication.getInstance().topActivity.sendMsg(1006, totalAmount+"-"+selfCode+"-"+driverCode+"-"+companyCode+"-"+powerOnTime+"-"+powerOffTime+"-"+KM+"-"+busiKM+"-"+carCount+"-"+tardeTime);
//					AppLog.e("------发送1006");

						SPUtils.setParam(SPConstants.SPK_signin, false);
						TTsFunction.speakText("签退成功");
						Activity top = MainApplication.getInstance().topActivity;
						if(top!=null){
							Intent intent = new Intent(top, ActivityEnd.class);
							intent.putExtra("info", totalAmount+"-"+selfCode+"-"+driverCode+"-"+companyCode+"-"+powerOnTime+"-"+powerOffTime+"-"+KM+"-"+busiKM+"-"+carCount+"-"+tardeTime);
							top.startActivity(intent);
						}

						// 下班签退
						byte[] message = Encoder.getCheckOut(meterData);
						LocalInfo info = new LocalInfo(LocalInfo.TYPE_CHECK_OUT);
						info.setData(Tools.parseByte2HexStr(message));
						LocalInfoBiz.getInstance().addInfo(info);
						LocalInfoBiz.getInstance().postCheckInfo();

						setRevertCheckIn();
					} catch (Exception e) {
						// TODO: handle exception
						AppLog.i(ExceptionUtil.getInfo(e));
					}
					break;
				case 0x0002: // 关机发送驾驶员从业资格信息应答
					try {
						// 操作结果
						int result = (Integer) dataList.get(dstPos++);
					} catch (Exception e) {
						// TODO: handle exception
						AppLog.i(ExceptionUtil.getInfo(e));
					}
					break;
				case 0x003C: // 关机结果
					try {
						// 退签类型
						// 操作结果
						int result = (Integer) dataList.get(dstPos++);
						if (result == 0x90) {
							// 数据
							byte[] meterData = (byte[]) dataList.get(dstPos++);
							DispatchCenterUsers.witeMsg(Encoder.getCheckOut(meterData), 0);
							DDUtil.sendText2TT(0);
						}
					} catch (Exception e) {
						// TODO: handle exception
						AppLog.i(ExceptionUtil.getInfo(e));
					}
					break;
				case 0x003A: // 临时（强制）开机
					try {
						// 操作结果
						int result = (Integer) dataList.get(dstPos++);
						if (result == 0x90) {
							// 数据
							byte[] meterData = (byte[]) dataList.get(dstPos++);
							String companyCode = Tools.byteToString(meterData, 0, 16);
							String driverCode = Tools.byteToString(meterData, 16, 19);
							String carNumber = Tools.byteToString(meterData, 35, 6);
							DeviceBiz.setCarNumber(carNumber);
							DeviceBiz.setCarNumberCorrection(false);
							// 64 总营运次数 UINT32
							int count = Integer.parseInt(Tools.parseByte2HexStr(Tools.byteTobyte(meterData, 63, 4)), 16);
							DispatchCenterUsers.witeMsg(Encoder.getCheckIn(Tools.byteTobyte(meterData, 0, 41), count), 0);
							DDUtil.sendText2TT(1);
						}
					} catch (Exception e) {
						// TODO: handle exception
						AppLog.i(ExceptionUtil.getInfo(e));
					}
					break;
				case 0x00F9: // 心跳?????已处理00E9正式心跳，这个F9是什么鬼？
					try {
						try {
							// 计价器当前状态--------------Decoder未发送有效数据到此
//						String state = (String) dataList.get(0);

							/**
							 * bit0（最低位）——空重车状； 0表示空车；1表示重车； bit1——停运状态； 0
							 * 表示停运，1表示营运
							 */
//						int kongzhong = Integer.parseInt(String.valueOf(state.charAt(0)));
//						int business = Integer.parseInt(String.valueOf(state.charAt(1)));
//						Constants.KONG_ZHONG_STATE = kongzhong + 1;

//						Constants.BUSINESS_STATE = business;
							// ConstantsState.setStateValue(3,
							// String.valueOf(business));


							/*
							 * //空重状态 0 表示空车；1 表示重车 String bit0 = state.substring(7,
							 * 8); ConstantsState.setStateValue(9,bit0); //停运（签退）状态
							 * 0 为签退，1 为营运 String bit1 = state.substring(6, 7);
							 * if(bit1.equals("1")){ ConstantsState.setStateValue(4,
							 * "0"); }else{ ConstantsState.setStateValue(4, "1"); }
							 * //开机状态 0 为正常情况 1 为强制开机 String bit2 =
							 * state.substring(5, 6); //关机状态 0 为正常情况 1 为强制关机 String
							 * bit3 = state.substring(4, 5); //异常速度信号 String bit7 =
							 * state.substring(0, 1);
							 */

						} catch (Exception e) {
							AppLog.e(ExceptionUtil.getInfo(e));
							e.printStackTrace();
						}
						break;
					} catch (Exception e) {
						// TODO: handle exception
						AppLog.i(ExceptionUtil.getInfo(e));
					}
					break;
				case 0x0000: // 计价器状态查询应答数据消息
					try {
						// 设备编号
						String deviceCode = (String) dataList.get(dstPos++);
						Log.e("计价器状态查询应答", "设备编号" + deviceCode);
						// 设备硬件版本号
						String deviceVersionCode = (String) dataList.get(dstPos++);
						Log.e("计价器状态查询应答", "设备硬件版本号" + deviceVersionCode);
						// 软件主版本号
						String softwareMajorVersionCode = (String) dataList.get(dstPos++);
						Log.e("计价器状态查询应答", "软件主版本号" + softwareMajorVersionCode);
						// 软件次版本号
						String softwareMinorVersionCode = (String) dataList.get(dstPos++);
						Log.e("计价器状态查询应答", "软件次版本号-" + softwareMinorVersionCode);
						// 设备状态
						int deviceStatus = (Integer) dataList.get(dstPos++);
						Log.e("计价器状态查询应答", "设备状态-" + deviceStatus);
						// 计价器工作状态
						int meterWorkStatus = (Integer) dataList.get(dstPos++);
						Log.e("计价器状态查询应答", "计价器工作状态-" + meterWorkStatus);
						// 车牌号
						carNumber = (String) dataList.get(dstPos++);
						Log.e("计价器状态查询应答", "车牌号-" + carNumber);
						// 公司代码
						companyCode = (String) dataList.get(dstPos++);
						Log.e("计价器状态查询应答", "公司代码-" + companyCode);
						// 司机从业资格证号
						driverQualificationCode = (String) dataList.get(dstPos++);
						Log.e("计价器状态查询应答", "司机从业资格证号-" + driverQualificationCode);
						// 总营运次数
						int operationAmount = (Integer) dataList.get(dstPos++);
						Log.e("计价器状态查询应答", "总营运次数-" + operationAmount);



					} catch (Exception e) {
						// TODO: handle exception
						AppLog.i(ExceptionUtil.getInfo(e));
					}
					break;
				case 0x0004: // 运价参数查询
					try {
						// 参数启用时间
						String paramsUpTime = (String) dataList.get(0);
						// 白天往返单价
						String dataAllPrice = (String) dataList.get(1);
						// 夜间往返单价
						String nightAllPrice = (String) dataList.get(2);
						// 白天单程单价
						String dataSinglePrice = (String) dataList.get(3);
						// 夜间单程单价
						String nightSinglePrice = (String) dataList.get(4);
						// 白天二次空贴单价
						String daySecondKtPrice = (String) dataList.get(5);
						// 夜间二次空贴单价
						String nightSecondKtPrice = (String) dataList.get(6);
						// 白天起步价
						String dayStartPrice = (String) dataList.get(7);
						// 夜间起步价
						String nightStartPrice = (String) dataList.get(8);
						// 续程里程数
						String xcMileage = (String) dataList.get(9);
						// 起程公里
						String startMileage = (String) dataList.get(10);
						// 单程公里
						String singleMileage = (String) dataList.get(11);
						// 二次空贴公里
						String secondKtMileage = (String) dataList.get(12);
						// 白天等候时间单价
						String dayWaitTimePrice = (String) dataList.get(13);
						// 夜间等候时间单价
						String nightWaitTimePrice = (String) dataList.get(14);
						// 免费等候时间
						String freeWaitTime = (String) dataList.get(15);
						// 加价时间
						String markupTime = (String) dataList.get(16);
						// 夜间开始时间
						String nightStartTime = (String) dataList.get(17);
						// 夜间结束时间
						String nightEndTime = (String) dataList.get(18);
						// RFU
						String rfu = (String) dataList.get(19);
						// 厂商自定义参数区
						String customParams = (String) dataList.get(20);
					} catch (Exception e) {
						// TODO: handle exception
						AppLog.i(ExceptionUtil.getInfo(e));
					}
					break;
				case 0x003B: // 锁定计价器应答
//				try {
//					// 操作结果
//					int result = (Integer) dataList.get(dstPos++);
//					if (result == 0x90) {
//						// 数据
//						byte[] meterData = (byte[]) dataList.get(dstPos++);
//						SendDateToSerial.witeSerialInfo("锁定计价器应答", EncoderSZ55aa.answerResult(String.valueOf(mid), SerialConstants.NAK));
//					}
//				} catch (Exception e) {
//					// TODO: handle exception
//					AppLog.i(ExceptionUtil.getInfo(e));
//				}
					break;
				case 0x003D: // 解锁计价器应答
					try {
						// 操作结果
						int result = (Integer) dataList.get(dstPos++);
					} catch (Exception e) {
						// TODO: handle exception
						AppLog.i(ExceptionUtil.getInfo(e));
					}
					break;
				case 0x003F: // 解锁计价器应答
					try {
						// 数据
						byte[] meterData = (byte[]) dataList.get(dstPos++);
					} catch (Exception e) {
						// TODO: handle exception
						AppLog.i(ExceptionUtil.getInfo(e));
					}
					break;
				case 0x00FF: // 升级应答
					try {
						// 操作结果 00：设备正确 01：设备不支持 02：同一版本，无须升级 03：标识信息不一致，无须升级
						// 04：执行错误
						int result = (Integer) dataList.get(dstPos++);
					} catch (Exception e) {
						// TODO: handle exception
						AppLog.i(ExceptionUtil.getInfo(e));
					}
					break;
			}
//			if (Constants.systemCheck) {
//				SysCheck.mHandler.obtainMessage(101).sendToTarget();
//			}
		} catch (Exception e) {
			AppLog.e(ExceptionUtil.getInfo(e));
			e.printStackTrace();
		}
	}

	public static void setRevertCheckIn(){
		SPUtils.setParam(SPConstants.SPK_ScardExist, false);
		SPUtils.setParam(SPConstants.SPK_faceSN, false);
	}

	/**
	 * 欢迎乘车播报
	 */
	private static void welcomeToRide(){
		try {
			final String presetTtsKey = SPUtils.getParamString(SPConstants.SPK_PRESET_TTS,"");
			AppLog.d(TAG,"welcomeToRide presetTtsKey:" + presetTtsKey);
			if(!TextUtils.isEmpty(presetTtsKey)){
				final String tts = SPUtils.getParamString(presetTtsKey,"");
				AppLog.d(TAG,"welcomeToRide tts:" + tts);
				if(!TextUtils.isEmpty(tts)){
					MainApplication.getInstance().handler.postDelayed(new Runnable() {
						@Override
						public void run() {
							try {
								TTsFunction.speakText(tts);
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					},10000);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
